<template>
  <div>
    <p-modal
      :visible="visible"
      :title="title"
      :width="1000"
      :z-index="1002"
      :mask-closable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div>
        <p-form-model
          :model="form"
          :rules="rules"
          layout="inline"
          :label-col="{ span: 5 }"
        >
          <p-form-model-item label="姓名">
            <p-input v-model="form.name" placeholder="请输入" />
          </p-form-model-item>
          <p-form-model-item label="部门">
            <p-input v-model="form.department" placeholder="请输入" />
          </p-form-model-item>
          <p-button type="primary" @click="getList(1)">搜索</p-button>
          <p-form-model-item label="职位">
            <p-input v-model="form.position" placeholder="请输入" />
          </p-form-model-item>
          <p-form-model-item label="联系电话 ">
            <p-input v-model="form.tel" placeholder="请输入" />
          </p-form-model-item>
          <p-button style="margin-left: auto" @click="handleReset">
            重置
          </p-button>
        </p-form-model>
        <!-- <p-button type="primary" @click="getContactListAdd">
          新增联系人
        </p-button> -->
        <p-table
          class="table-list-container"
          row-key="id"
          :scroll="{ x: '100%', y: 'calc(100vh - 450px)' }"
          :columns="columns"
          bordered
          :loading="loading"
          :pagination="paginationMixin"
          :row-selection="rowSelectionMixin"
          :data-source="dataSource"
          @change="handleTableChange"
        >
          <!-- <a
            slot="name"
            slot-scope="text, record"
            @click="handleNumberClick(record)"
          >
            {{ text }}
          </a> -->
        </p-table>
      </div>
    </p-modal>
  </div>
</template>

<script>
import { postCustomerList, postleadsContact } from '@/api/clue.js';
import { postBusinessContact } from '@/api/business';
import mixinTable from '@/mixins/mixin-table.js';
const defaultForm = {
  name: undefined,
  department: undefined,
  position: undefined,
  tel: undefined,
};
export default {
  mixins: [mixinTable],
  props: {
    title: {
      type: String,
      default: '选择联系人',
    },
    value: {
      type: [String, Number],
      default: undefined,
    },
    list: {
      type: Array,
      default: () => [],
    },
    index: {
      type: Number,
      default: 0,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    opportunityId: {
      type: [String, Number],
      default: undefined,
    },
    leadsNo: {
      type: [String, Number],
      default: undefined,
    },
    customerCode: {
      type: [String, Number],
      default: undefined,
    },
  },
  data() {
    return {
      parentId: '1',
      detail: {},
      planId: undefined,
      asc: true,
      form: {
        ...defaultForm,
      },
    };
  },
  computed: {
    rankOptions() {
      return this.$store.state.dictionary.dict['rank_code'] || {};
    },
    rankStatusOptions() {
      return {
        1: '正常',
        2: '冻结',
      };
    },
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          width: 60,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '姓名',
          width: 150,
          ellipsis: true,
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
        },
        {
          align: 'center',
          title: '状态',
          width: 150,
          ellipsis: true,
          dataIndex: 'contactStatus',
          customRender: text => this.rankStatusOptions[text],
        },
        {
          align: 'center',
          title: '部门',
          width: 150,
          ellipsis: true,
          dataIndex: 'department',
        },
        {
          align: 'center',
          title: '职位',
          width: 150,
          ellipsis: true,
          dataIndex: 'position',
        },
        {
          align: 'center',
          title: '职级',
          width: 150,
          ellipsis: true,
          dataIndex: 'rankCode',
          customRender: text => this.rankOptions[text],
        },
        {
          align: 'center',
          title: '联系电话',
          width: 150,
          ellipsis: true,
          dataIndex: 'tel',
        },
        {
          align: 'center',
          title: '性别',
          width: 150,
          ellipsis: true,
          dataIndex: 'gender',
          customRender(t) {
            return t === null ? '-' : t === 0 ? '男' : '女';
          },
        },
        {
          align: 'center',
          title: '邮箱',
          width: 150,
          ellipsis: true,
          dataIndex: 'email',
        },
      ];
      return columns;
    },
  },
  watch: {
    visible: {
      handler(val) {
        val && this.getList();
        val && this.getSelect();
      },
    },
    immediate: true,
  },
  created() {},
  methods: {
    getSelect() {
      const codes = this.list.map(item => item.contactId);
      this.rowSelectionMixin.getCheckboxProps = record => {
        return {
          props: {
            disabled: codes.includes(record.id),
          },
        };
      };
    },
    getSearchForm() {
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
        column: this.columnKey,
      };
      return {
        ...this.form,
        ...page,
        cname: this.customerCode,
      };
    },
    // 搜索线索列表
    async getList(val) {
      if (val) {
        this.paginationMixin.current = 1;
      }
      const form = this.getSearchForm();
      this.loading = true;
      const result = await postCustomerList(form).finally(
        () => (this.loading = false)
      );
      this.dataSource = result.data.data?.records;
      this.paginationMixin.total = result.data.data?.total;
    },
    // 重置
    handleReset() {
      this.form = { ...defaultForm };
      this.paginationMixin.current = 1;
      this.getList();
    },

    handleOrgChange(val) {
      if (!val) return;
      this.parentId = val;
      (this.form.kamp = ''), (this.form.salesGroup = '');
    },
    handleSearch() {
      this.visible = true;
    },
    handleCancel() {
      this.$emit('update:visible', false);
      this.rowSelectionMixin.selectedRowKeys = [];
      this.$emit('fresh');
    },
    // 选择联系人
    async handleOk() {
      const selectedRowKeys = this.rowSelectionMixin.selectedRowKeys || [];
      if (!selectedRowKeys.length) {
        this.$message.info(
          `请选择关联联系人，现有 ${selectedRowKeys.length} 条！`
        );
        return;
      }
      const selectedInfos = this.rowSelectionMixin.selectedRows.map(
        (item, i) => {
          return {
            contactId: item.id,
            leadsNo: this.leadsNo,
            opportunityId: this.opportunityId,
            bizType: '1',
          };
        }
      );
      if (this.opportunityId) {
        await postBusinessContact(selectedInfos);
      } else {
        await postleadsContact(selectedInfos);
      }
      this.$message.success('关联成功');
      this.handleCancel();
    },
    // 编号点击
    handleNumberClick(record) {
      this.$message.warning('该功能暂未实现！');
    },
    getContactListAdd() {
      this.$router.push({
        path: '/customer-management',
        query: {},
      });
    },
    // 分页
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.getList();
    },
  },
};
</script>

<style lang="less" scoped>
.content-container {
  width: 100%;
  display: flex;
  align-items: center;
  .content {
    display: flex;
    justify-content: center;
    flex: 1;
  }
}
.table-list-container {
  margin-top: 20px;
}
.poros-form {
  box-sizing: border-box;
  background-color: #f7f7f8;
  padding: 10px;
  padding-bottom: 0px;
  width: 100%;
}
.poros-form-item {
  width: 33%;
  margin: 0 30px 10px;
}
/deep/ .poros-form-item-control-wrapper {
  width: calc(100% - 70px);
}
.btn-search {
  margin-right: 16px;
}
</style>
